<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/12 0012
 * Time: 08:30
 */
namespace app\admin\validate;

use app\admin\model\SystemUser;
use think\captcha\Captcha;
use think\Validate;
class User extends Validate
{

    protected $rule = [
        'username'          =>  'require|min:5|max:15|checkLogin|token',
        'password'          =>  'require|checkPass',
        'verify'            =>  'require|checkVerify',
    ];

    protected $message = [
        'username.require'  =>  '用户名不能为空',
        'username.min:5'    =>  '用户名至少 5 个但不超过 15 个字符',
        'username.max:15'   =>  '用户名至少 5 个但不超过 15 个字符',
        'password'          =>  '密码不能为空',
        'verify'            =>  '验证码不能为空',
    ];
    //场景
    protected $scene = [
        'login'             =>  ['username','password','verify'],
    ];

    // 自定义验证规则
    //验证账号
    protected function checkLogin(){
        $username = input('username','','trim');
        $system_user = SystemUser::where('username',$username)->find();
        return (isset($system_user->id) && $system_user->id) ? true : '用户不存在';
    }
    //验证密码
    protected function checkPass(){
        $username = input('username','','trim');
        $password = input('password','','trim');
        //获取密码和盐值字段
        $system_user = SystemUser::where('username',$username)->field('password,salt')->find();
        $password = md5(md5(trim($password)).$system_user->salt);
        return $password === $system_user->password ? true : '密码不正确';
    }
    //验证验证码
    protected function checkVerify(){
        $verify = input('verify','','trim');
        $Captcha = new Captcha();
        return $Captcha->check($verify) ? true : '验证码不正确';
    }
}